<?php
/**
 * Created by Administrator
 * User: longli
 * Date: 2020/08/12
 * Time: 10:50
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use think\facade\Log;

/**
 * joom 接口服务
 * Class JoomService
 * @package app\common\service\joom
 * @link https://www.showdoc.com.cn/186698173532010?page_id=1069681597490866
 */
class JoomService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'client_id',
                'field' => 'client_id',
            ],
            [
                'type' => 'text',
                'name' => 'client_secret',
                'field' => 'client_secret',
            ],
            [
                'type' => 'text',
                'name' => 'refresh_token',
                'field' => 'refresh_token',
            ],
        ],
        'option' => [ // 可选字段
            [
                'type' => 'text',
                'name' => 'access_token',
                'field' => 'access_token',
                'readonly' => true,
            ],
        ],
    ];

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 要抓取的时间，默认为今天</li>
     * <li>int page_size 每页多少条，默认100</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return array|bool
     * @date 2020/08/13
     * @author longli
     */
    public function getOrderList($params = [], $replace = false)
    {
        Log::info(sprintf("Joom 批量同步账号【%d】订单，请求参数: 【%s】", $this->getAccountId(), json_encode($params)));
        $startSyncTime = time();
        $account = $this->getAccount();
        $startDate = !empty($params['start_date']) ? $params['start_date'] : date('Y-m-d');
        $limit = !empty($params['page_size']) ? $params['page_size'] : 100;
        $url = $this->getBaseUrl() . "/order/multi-get?access_token={$account->token->access_token}&limit={$limit}&since=$startDate";
        $refresh = 0;
        do
        {
            $response = Tools::curlGet($url);
            if(!$response['status'] || !Tools::isJson($response['data'], $orderData) || $orderData['code'] != 0)
            {
                if(!empty($orderData['code']))
                {
                    if($refresh++ > 3) break;
                    $this->refreshToken(); // 刷新 token
                    continue;
                }
                Log::info(sprintf("Joom 账号【%d】同步订单失败, 提示信息:【%s】", $this->getAccountId(), $response['data']));
                break;
            }
            if(empty($orderData['data'])) break; // 订单为空

            // 获取下一页请求地址
            $url = !empty($orderData['paging']['next']) ? $orderData['paging']['next'] : '';
            foreach($orderData['data'] as $order)
            {
                $order = $order['Order'];
                $this->pushOrderToTemp($order['order_id'], $order, $replace);
            }
        }while(!empty($url));
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $params);
    }

    /**
     * 刷新授权
     * @date 2020/08/13
     * @author longli
     * @return bool
     */
    public function refreshToken()
    {
        $account = $this->getAccount();
        $url = $this->getBaseUrl() . "/oauth/refresh_token?client_id={$account->token->client_id}&client_secret={$account->token->client_secret}&refresh_token={$account->token->refresh_token}&grant_type=refresh_token";
        $params = [
            "client_id" => $account->token->client_id,
            "client_secret" => $account->token->client_secret,
            "grant_type" => "refresh_token",
            "refresh_token" => $account->token->refresh_token,
        ];
        Log::info(sprintf("Joom 账号【%d】刷新 token, 参数:【%s】", $this->getAccountId(), json_encode($params)));
        $response = Tools::curlPost($url, $params);
        if(!$response['status'] || !Tools::isJson($response['data'], $jsonData) || $jsonData['code'] != 0)
        {
            Log::info(sprintf("Joom 账号【%d】刷新 token 失败, 提示信息:【%s】", $this->getAccountId(), $response['data']));
            return false;
        }
        // 保存 token
        $account->token->access_token = $jsonData["data"]["access_token"];
        $account->save();
        return true;
    }

    /**
     * @inheritDoc
     */
    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $attr = "";
        if(!empty($data['color'])) $attr .= "{$data['color']}-";
        if(!empty($data['size'])) $attr .= $data['size'];
        $info = [
            "item_id"       => $data['product_id'], // 商品 id
            "qty"           => $data['quantity'], // 数量
            "return_qty"    => 0, // 取消数量
            "price"         => $data['price'], // 售价
            "platform_sku"  => $data['sku'], // sku
            "name"          => $data['product_name'], // 产品名称
            "image"         => $data['product_image_url'], // 图片地址
            'attr'          => $attr, // 产品属性
        ];
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $address = $data['ShippingDetail'];
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data["state"], // 订单在平台的状态
            "consignee"                 => $address['name'], // 收件人
            "buyer_phone"               => $address["phone_number"], // 电话
            "buyer_country_code"        => $address['country'], // 国家编码
            "buyer_city"                => $address['city'], // 城市
            "buyer_province"            => $address['state'], // 省
            "buyer_post_code"           => $address['zipcode'], // 邮编
            "buyer_address_1"           => $address['street_address1'], // 买家收货地址1
            "buyer_address_2"           => $address['street_address2'], // 买家收货地址2
            "order_source_create_time"  => $this->parseTimeToDate($data['order_time']), // 订单在平台生成的时间
            "order_price"               => $data['price'], // 订单金额
            "total_price"               => $data['order_total'], // 订单总金额
            "commission_cost"           => $data['price'] - $data['cost'], // 订单总金额
            "currency"                  => 'RUB', // 币种
            "platform_remark"           => "", // 买家备注信息
            "shipping_price"            => $data["shipping"], // 买家支付运费
            "shipping_method"           => $data["shipping_method"], // 物流方式
            "shipping_code"             => $data["tracking_number"], // 运单号
            "tracking_number_time"      => Tools::now(), // 更新运单号时间
            "logistics_name"            => $data['shipping_provider'], // 物流商
            "order_detail" => [$info],
        ];
        return OrderService::getInstance()->addOrder($order);
    }
}